package com.bit.forum.controller;

import ch.qos.logback.core.joran.action.IADataForComplexProperty;
import com.bit.forum.common.AppResult;
import com.bit.forum.common.ResultCode;
import com.bit.forum.config.AppConfig;
import com.bit.forum.model.Article;
import com.bit.forum.model.ArticleReply;
import com.bit.forum.model.User;
import com.bit.forum.services.IArticleReplyService;
import com.bit.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "回复接口")
@RestController
@Slf4j
@RequestMapping("/reply")
public class ArticleReplayController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleReplyService articleReplyService;

    @ApiOperation("回复帖子")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @ApiParam("帖子Id") @RequestParam("articleId") @NonNull Long articleId,
                             @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);

        }
        Article article = articleService.selectById(articleId);
        if(article == null||article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        articleReplyService.create(articleReply);
        return AppResult.success();
    }
    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesBiArticleId(@ApiParam("帖子Id") @RequestParam("articleId") @NonNull Long articleId){
        Article article = articleService.selectById(articleId);
        if(article == null|| article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        return AppResult.success(articleReplies);
    }
}
